package org.bigk.invoices.dao;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.bigk.invoices.exceptions.DBAccessException;
import org.bigk.invoices.model.User;
import org.bigk.invoices.utils.HibernateUtils;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;

public class UsersDAOImpl implements UsersDAO {
	/**
	 * Logger for this class
	 */
	private static final Log logger = LogFactory.getLog(UsersDAOImpl.class);

	@Override
	public User getUser(Long id) throws DBAccessException {
		if (logger.isDebugEnabled()) {
			logger.debug("getUser(Long id=" + id + ") - start");
		}

		User user = null;
		Session session = null;
		try {
			session = HibernateUtils.getCurrentSession();
			user = (User) session.get(User.class, id);
		} catch (HibernateException ex) {
			logger.error("getUser(Long)", ex);
			throw new DBAccessException(ex);
		}

		if (logger.isDebugEnabled()) {
			logger.debug("getUser(Long) - end - return value=" + user);
		}
		return user;
	}

	@Override
	public User getUser4Login(String login) throws DBAccessException {
		if (logger.isDebugEnabled()) {
			logger.debug("getUser4Login(String login=" + login + ") - start");
		}
		
		User user = null;
		Session session = null;

        try {
			session = HibernateUtils.getCurrentSession();

            Criteria crit = session.createCriteria(User.class);
            crit.add(Restrictions.eq("login", login));
            user = (User) crit.uniqueResult();
            
        } catch(HibernateException ex) {
			logger.error("getUser4Login(String)", ex);
        	throw new DBAccessException(ex);
        }

		if (logger.isDebugEnabled()) {
			logger.debug("getUser4Login(String) - end - return value=" + user);
		}
        return user;
	}

	public static void main(String[] args) throws Exception {
		UsersDAO dao = new UsersDAOImpl();
		User u = dao.getUser(new Long(2));
		
		System.out.println(u);
	}
}
